/* com_writer.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>

#define BUFFER_SIZE 1024
char *dev[] = {"/dev/ttyS0","/dev/ttyUSB1","/dev/ttyUSB2","/dev/ttyUSB3","/dev/ttyUSB4"};
int g_timeout = 10; 
/*打开串口函数*/
int open_port(void)
{
	int fd,i;
	
	/* 打开串口 */
	for(i = 0; i < sizeof(dev)/sizeof(char*); i++)
	{
		fd = open(dev[i], O_RDWR|O_NOCTTY|O_NDELAY);
		if(fd < 0)
		{
			printf("%s\n",dev[i]);
			perror("open failed");
			continue;
		}
		else
		{
			break;
		}
	}	
	if (fd < 0)
	{
		perror("open serial port failed");
		return(-1);
	}
	else
	{
	//	printf("open serial port: %s successed!\n",dev[i]);
	}
#if 0
	/*恢复串口为阻塞状态*/
	if (fcntl(fd, F_SETFL, 0) < 0)
	{
		perror("fcntl F_SETFL");
	}
#else
	int flags;
	flags = fcntl(fd,F_GETFL,0);
	flags |= O_NONBLOCK;
	fcntl(fd,F_SETFL,flags);
#endif	  
	/*测试是否为终端设备*/
	if (isatty(STDIN_FILENO) == 0)
	{
		perror("standard input is not a terminal device");
	}
	return fd;
}
int set_com_config(int fd,int baud_rate,int data_bits, char parity, int stop_bits)
{
	struct termios new_cfg,old_cfg;
	int speed;
	/*保存并测试现有串口参数设置,在这里如果串口号等出错,会有相关的出错信息*/
	if (tcgetattr(fd, &old_cfg) != 0)
	{
		perror("tcgetattr");
		return -1;
	}
	/* 设置字符大小*/
	new_cfg = old_cfg;
	cfmakeraw(&new_cfg); /* 配置为原始模式 */
	new_cfg.c_cflag &= ~CSIZE;
	/*设置波特率*/
	switch (baud_rate)
	{
		case 2400:
			{
				speed = B2400;
			}
			break;
		case 4800:
			{
				speed = B4800;
			}
			break;
		case 9600:
			{
				speed = B9600;
			}
			break;
		case 19200:
			{
				speed = B19200;
			}
			break;
		case 38400:
			{
				speed = B38400;
			}
			break;
		case 1000000:
			{
				speed = 1000000;
			}
			break;
		case 4000000:
			{
				//speed = B400000;//B4194304;
				speed = B4000000;
			}
		break;
		default:
			break;
	}
	//cfsetispeed(&new_cfg, B4000000);
	//cfsetospeed(&new_cfg, B4000000);
	cfsetispeed(&new_cfg, B115200);
	cfsetospeed(&new_cfg, B115200);
	/*设置停止位*/
	switch (data_bits)
	{
		case 7:
			{
				new_cfg.c_cflag |= CS7;
			}
			break;
		default:
		case 8:
			{
				new_cfg.c_cflag |= CS8;
			}
			break;
	}
	/*设置奇偶校验位*/
	switch (parity)
	{
		default:
		case 'n':
		case 'N':
			{
				new_cfg.c_cflag &= ~PARENB;
				new_cfg.c_iflag &= ~INPCK;
			}
			break;
		case 'o':
		case 'O':
			{
				new_cfg.c_cflag |= (PARODD | PARENB);
				new_cfg.c_iflag |= INPCK;
			}
			break;
		case 'e':
		case 'E':
			{
				new_cfg.c_cflag |= PARENB;
				new_cfg.c_cflag &= ~PARODD;
				new_cfg.c_iflag |= INPCK;
			}
			break;
		case 's': /*as no parity*/
		case 'S':
			{
				new_cfg.c_cflag &= ~PARENB;
				new_cfg.c_cflag &= ~CSTOPB;
			}
			break;
	}
	/*设置停止位*/
	switch (stop_bits)
	{
		default:
		case 1:
			{
				new_cfg.c_cflag &= ~CSTOPB;
			}
			break;
		case 2:
			{
				new_cfg.c_cflag |= CSTOPB;
			}
	}
	/*设置等待时间和最小接收字符*/
	new_cfg.c_cc[VTIME] = 0;
	new_cfg.c_cc[VMIN] = 1;
	/*处理未接收字符*/
	tcflush(fd, TCIFLUSH);
	/*激活新配置*/
	if ((tcsetattr(fd, TCSANOW, &new_cfg)) != 0)
	{
		perror("tcsetattr");
		return -1;
	}
	return 0;
}
int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop)
{
    struct termios newtio,oldtio;
    if ( tcgetattr( fd,&oldtio) != 0) {
        perror("SetupSerial 1");
        return -1;
    }
    bzero( &newtio, sizeof( newtio ) );
    newtio.c_cflag |= CLOCAL | CREAD;
    newtio.c_cflag &= ~CSIZE;

    switch ( nBits )
    {
    case 7:
        newtio.c_cflag |= CS7;
        break;
    case 8:
        newtio.c_cflag |= CS8;
        break;
    }

    switch ( nEvent )
    {
    case 'O':
        newtio.c_cflag |= PARENB;
        newtio.c_cflag |= PARODD;
        newtio.c_iflag |= (INPCK | ISTRIP);
        break;
    case 'E':
        newtio.c_iflag |= (INPCK | ISTRIP);
        newtio.c_cflag |= PARENB;
        newtio.c_cflag &= ~PARODD;
        break;
    case 'N':
        newtio.c_cflag &= ~PARENB;
        break;
    }

    switch ( nSpeed )
    {
    case 2400:
        cfsetispeed(&newtio, B2400);
        cfsetospeed(&newtio, B2400);
        break;
    case 4800:
        cfsetispeed(&newtio, B4800);
        cfsetospeed(&newtio, B4800);
        break;
    case 9600:
        cfsetispeed(&newtio, B9600);
        cfsetospeed(&newtio, B9600);
        break;
    case 115200:
        cfsetispeed(&newtio, B115200);
        cfsetospeed(&newtio, B115200);
        break;
    case 1048576:
        cfsetispeed(&newtio, B1000000);
        cfsetospeed(&newtio, B1000000);
        break;
    case 460800:
        cfsetispeed(&newtio, B460800);
        cfsetospeed(&newtio, B460800);
        break;
    case 921600:
        cfsetispeed(&newtio, B921600);
        cfsetospeed(&newtio, B921600);
        break;  
    case 1152000:
        cfsetispeed(&newtio, B1152000);
        cfsetospeed(&newtio, B1152000);
        break;      
    case 1000000:
        cfsetispeed(&newtio, B1000000);
        cfsetospeed(&newtio, B1000000);
        break;  
    case 2500000:
        cfsetispeed(&newtio, B2500000);
        cfsetospeed(&newtio, B2500000);
        break;  
    case 3000000:
        cfsetispeed(&newtio, B3000000);
        cfsetospeed(&newtio, B3000000);
        break;          
    case 3500000:
        cfsetispeed(&newtio, B3500000);
        cfsetospeed(&newtio, B3500000);
        break;          
    case 4000000:
        cfsetispeed(&newtio, B4000000);
        cfsetospeed(&newtio, B4000000);
        break;              
    default:
        cfsetispeed(&newtio, B9600);
        cfsetospeed(&newtio, B9600);
        break;
    }

    if ( nStop == 1 )
        newtio.c_cflag &= ~CSTOPB;
    else if ( nStop == 2 )
        newtio.c_cflag |= CSTOPB;
    
    newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/
    newtio.c_oflag &= ~OPOST; /*Output*/
    newtio.c_cc[VTIME] = g_timeout/100; //单位：1/10s
    newtio.c_cc[VMIN] = 0;
    tcflush(fd,TCIFLUSH);
    if ((tcsetattr(fd,TCSANOW,&newtio))!=0)
    {
        perror("com set error");
        return -1;
    }

    return 0;
}



int open_and_wr_serial(u_int8_t* data, int len, u_int8_t* out_data, int out_buf_len, int* r_len)
{
	int fd;
	
	if((fd = open_port()) < 0) /* 打开串口 */
	{
		printf("tty open failed!\r\n");
		return 1;
	}

	set_opt(fd, 4000000, 8, 'N', 1);
	write(fd, data, len);
	int tmp_len = 0;
	int offset_len = 0;

	int timeout = 3000;  //3s=1ms*3000
	do{
		usleep(1000);
		tmp_len = read(fd, out_data+offset_len, out_buf_len-offset_len);
		offset_len += tmp_len;

		if ((offset_len == 0) && (timeout))  //没有从串口读取到数据
		{
			timeout--;
		}
		else
		{
			timeout = 0;
		}
	}while(tmp_len>0 || timeout);
	*r_len = offset_len;
	
	close(fd);
	
	return 0;
}
